<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="栏目标题" prop="navigationName">
        <el-input
          v-model="queryParams.navigationName"
          placeholder="请输入栏目标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input
          v-model="queryParams.sort"
          placeholder="请输入排序"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="图标" prop="icon">
        <el-input
          v-model="queryParams.icon"
          placeholder="请输入图标"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fetv:context:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['fetv:context:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fetv:context:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fetv:context:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table
      v-loading="loading"
      :data="contextList"
      row-key="id"
      @selection-change="handleSelectionChange"
      default-expand-all
      lazy
      :load="load"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      >
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <!--            用不到-->
      <!--            <el-table-column label="id" align="center" prop="id" />-->
      <!--            <el-table-column label="父栏目id" align="center" prop="parentId" />-->
      <el-table-column label="父栏目" align="center" prop="parentName"/>
      <el-table-column label="栏目标题" align="center" prop="navigationName"/>
      <el-table-column label="是否主菜" align="center" prop="isPrimary">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fetv_no_yes" :value="scope.row.isPrimary"/>
        </template>
      </el-table-column>
      <el-table-column label="模块分类" align="center" prop="moduleClassify">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fetv_module_type" :value="scope.row.moduleClassify"/>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort"/>
      <el-table-column label="图标" align="center" prop="icon">
        <template slot-scope="scope">
          <image-preview :src="scope.row.icon"/>
        </template>
      </el-table-column>
      <el-table-column label="是否推荐" align="center" prop="isRecommend">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fetv_no_yes" :value="scope.row.isRecommend"/>
        </template>
      </el-table-column>
      <el-table-column label="跳转方式" align="center" prop="jumpMode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fetv_jump_mode" :value="scope.row.jumpMode"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fetv_yes_no" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fetv:context:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAdd(scope.row.id)"
            v-hasPermi="['fetv:context:add']"
          >添加子栏目
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fetv:context:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleStatus(scope.row)"
            v-hasPermi="['fetv:school:edit']"
          >
            <div v-if="scope.row.status == 0">禁用</div>
            <div v-else>启用</div>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--    <pagination-->
    <!--      v-show="total>0"-->
    <!--      :total="total"-->
    <!--      :page.sync="queryParams.pageNum"-->
    <!--      :limit.sync="queryParams.pageSize"-->
    <!--      @pagination="getList"-->
    <!--    />-->

    <!-- 添加或修改栏目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父栏目" prop="parentId">
          <el-select
            v-model="form.parentId"
            filterable
            remote
            reserve-keyword
            placeholder="顶级节点"
            :remote-method="fetchParentDictLabel"
            @focus="fetchParentDictLabel('')"
            :loading="SelectLoading">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <!--          <el-input v-model="form.navigationName" placeholder="请输入栏目标题"/>-->
        </el-form-item>
        <el-form-item label="栏目标题" prop="navigationName">
          <el-input v-model="form.navigationName" placeholder="请输入栏目标题"/>
        </el-form-item>
        <el-form-item label="是否主菜" prop="isPrimary">
          <el-radio v-model="form.isPrimary" :label="0">否</el-radio>
          <el-radio v-model="form.isPrimary" :label="1">是</el-radio>
        </el-form-item>
        <el-form-item label="模块分类" prop="moduleClassify">
          <el-select v-model="form.moduleClassify" placeholder="请选择模块的类型">
            <el-option
              v-for="dict in dict.type.fetv_module_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序"/>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <image-upload
            v-model="form.icon"
            :limit="1"
          />
        </el-form-item>
        <el-form-item label="是否推荐" prop="isRecommend">
          <el-radio v-model="form.isRecommend" :label="0">否</el-radio>
          <el-radio v-model="form.isRecommend" :label="1">是</el-radio>
        </el-form-item>
        <el-form-item label="跳转方式" prop="jumpMode">
          <el-select v-model="form.jumpMode" placeholder="请选择跳转方式">
            <el-option
              v-for="dict in dict.type.fetv_jump_mode"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio v-model="form.status" :label="0">开启</el-radio>
          <el-radio v-model="form.status" :label="1">禁用</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addContext,
  delContext,
  getContext,
  getLabel,
  listContext,
  listContextPrimary,
  updateContext
} from "@/api/fetv/context";

export default {
  name: "Context",
  dicts: ["fetv_module_type", "fetv_jump_mode", "fetv_yes_no", "fetv_no_yes"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 栏目表格数据
      contextList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        parentId: null,
        navigationName: null,
        isPrimary: null,
        moduleClassify: null,
        sort: null,
        icon: null,
        isRecommend: null,
        jumpMode: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        navigationName: [
          {required: true, message: "栏目标题不能为空", trigger: "blur"},
        ],
        isPrimary: [
          {required: true, message: "是否主菜不能为空", trigger: "blur"},
        ],
        moduleClassify: [
          {required: true, message: "模块分类不能为空", trigger: "blur"},
        ],
        jumpMode: [
          {required: true, message: "跳转方式不能为空", trigger: "blur"},
        ]
      },
      //   远程选项
      options: [],
      //   遮罩
      SelectLoading: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 加载子节点*/
    load(tree, treeNode, resolve) {
      console.log(tree, treeNode, resolve)
    },
    /** 获得远程的栏目标签
     *
     */
    fetchParentDictLabel(query) {
      this.SelectLoading = true;
      getLabel(query).then(res => {
        this.options = res;
      }).finally(() => {
          this.options.unshift({
            id: 0,
            name: "顶级节点"
          })
          this.SelectLoading = false;
        }
      );
    },
    /** 查询栏目列表 */
    async getList() {
      this.loading = true;
      listContext(this.queryParams).then(response => {
        const data = response.rows
        // // 树形表转化
        this.contextList = this.toTree(data)
        this.total = response.total;
      }).finally(() => {
        this.loading = false;
      });

      // 分层          方便分页
      // const res = await this.getListPrimary(0)
      // this.contextList = res.data;
      // this.total = res.total;
      // this.loading = false;
    },
    /** 查询栏目列表分层 */
    async getListPrimary(parentId) {
      if (parentId !== undefined) {
        this.queryParams.parentId = parentId;
      } else {
        this.queryParams.parentId = 0;
      }
      const response = await listContextPrimary(this.queryParams)
      const data = {
        data: this.toTree(response.rows),
        total: response.total
      };
      return data;
    },
    /**表格转化为树形表*/
    toTree(data) {
      let map = {};
      let result = [];
      for (let i = 0; i < data.length; i++) {
        map[data[i].id] = i;
        data[i].children = []
      }
      for (let i = 0; i < data.length; i++) {
        let node = data[i];
        if (node.parentId !== 0) {
          if (map[node.parentId] !== undefined) {
            data[map[node.parentId]].children.push(node);
          } else {
            result.push(node);
          }
        } else {
          result.push(node);
        }
      }
      return result;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        navigationName: null,
        isPrimary: null,
        moduleClassify: null,
        sort: null,
        icon: null,
        isRecommend: null,
        jumpMode: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 修改状态操作 */
    handleStatus(row) {
      this.reset();
      const id = row.id || this.ids
      /** 发送请求*/
      this.form.id = id;
      this.form.status = row.status ^ 1;
      updateContext(this.form).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        this.getList();
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(parentId) {
      this.reset();
      if (typeof parentId === "number") {
        this.form.parentId = parentId;
      }
      this.open = true;
      this.title = "添加栏目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getContext(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改栏目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateContext(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContext(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除栏目编号为"' + ids + '"的数据项？').then(function () {
        return delContext(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fetv/context/export', {
        ...this.queryParams
      }, `context_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
